package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.mobile.vo.common.NoticeMessageVO;
import com.niiwoo.civet.mobile.vo.response.AppDownloadResponseVO;
import com.niiwoo.civet.mobile.vo.response.HomePageInfoVO;
import com.niiwoo.civet.mobile.vo.response.HomePageMessageHintResponseVO;
import com.niiwoo.civet.mobile.vo.response.NiiwooNoticeMessageVO;
import com.niiwoo.civet.mobile.vo.response.NoticeMessageResponseVO;
import com.niiwoo.civet.mobile.vo.response.loan.LoanBusinessVo;
import com.niiwoo.civet.trade.dto.common.LoanBusinessInfoDTO;
import com.niiwoo.civet.trade.dto.response.statisticsinfo.StatisticsInfoResponseDTO;
import com.niiwoo.civet.trade.service.ProjectCommonDubboService;
import com.niiwoo.civet.trade.service.loan.LoanBusinessDubboService;
import com.niiwoo.civet.trade.service.statisticsinfo.StatisticsInfoDubboService;
import com.niiwoo.civet.user.dto.NoticeMessageDTO;
import com.niiwoo.civet.user.dto.request.HomePageMessageHintRequestDTO;
import com.niiwoo.civet.user.dto.response.HomePageMessageHintResponseDTO;
import com.niiwoo.civet.user.enums.ProductTypeEnum;
import com.niiwoo.civet.user.service.HomePageDubboService;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.shiro.UserAuthPrincipal;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dell on 2017/12/15. Description：civet-parent
 */
@Slf4j
@RestController
@RequestMapping("/homePage")
@Api(tags = "主页", description = "/homePage")
public class HomePageController extends BaseController {

	@Reference(version = "1.0.0")
	private LoanBusinessDubboService loanBusinessDubboService;
	@Reference(version = "1.0.0")
	private HomePageDubboService homePageDubboService;
	@Reference(version = "1.0.0")
	private StatisticsInfoDubboService statisticsInfoDubboService;
	@Reference(version = "1.0.0")
	private ProjectCommonDubboService projectCommonDubboService;

	@Value("${h5-https-url}")
	private String h5HttpsURL;

	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@AuthIgnore
	@ApiOperation("获取首页基本信息（凡凯）")
	@PostMapping("/homePageInfo")
	public Result<HomePageInfoVO> homePageInfo() {
		HomePageInfoVO responseVO = new HomePageInfoVO();
		StatisticsInfoResponseDTO responseDTO = statisticsInfoDubboService.queryStatisticsInfo();
		responseVO.setRegisterUserCount(Long.parseLong(responseDTO.getRegisterUserCount()));
		responseVO.setCumulativeTradeAmount(new BigDecimal(responseDTO.getCumulativeTradeAmount()));
		responseVO.setNewNoticeId(homePageDubboService.newestNoticeId());
		responseVO.setServerTime(FastDateFormat.getInstance(DateUtils.SHOW_DATETIME_FORMAT).format(new Date()));
		return Result.with(responseVO);
	}

	@AuthIgnore
	@ApiOperation("首页消息（通知/公告）信息")
	@PostMapping("/homePageMessageHint")
	public Result<HomePageMessageHintResponseVO> homePageMessageHint() {
		HomePageMessageHintResponseVO responseVO = new HomePageMessageHintResponseVO();
		HomePageMessageHintRequestDTO requestDTO = new HomePageMessageHintRequestDTO();
		requestDTO.setUserId(PrincipalContext.getUserId());
		HomePageMessageHintResponseDTO responseDTO = homePageDubboService.homePageMessageHint(requestDTO);
		BeanUtils.copyProperties(responseDTO, responseVO);
		return Result.with(responseVO);
	}

	@AuthIgnore
	@ApiOperation("获取你我金融公告列表接口（凡凯）")
	@PostMapping("/postNiiwooNoticeList")
	public Result<NoticeMessageResponseVO> postNiiwooNoticeList(@RequestBody NoticeMessageVO requestVO) {
		NoticeMessageResponseVO responseVO = new NoticeMessageResponseVO();
		log.info("获取你我金融公告列表接口");
		try {
			UserAuthPrincipal principal = (UserAuthPrincipal) SecurityUtils.getSubject().getPrincipal();
			String userId = "";
			if (Objects.nonNull(principal)) {
				userId = principal.getUserId();
			}

			// 查询公告列表
			Map<String, Object> result = homePageDubboService.postNiiwooNoticeList(requestVO.getPageNumber(), requestVO.getPageSize(), userId);
			responseVO.setTotalCount((Integer) result.get("totalCount"));
			responseVO.setTotalPage((Integer) result.get("totalPage"));

			List<NoticeMessageDTO> noticeMessageDTOS = (List<NoticeMessageDTO>) result.get("noticeList");
			if (noticeMessageDTOS != null && noticeMessageDTOS.size() > 0) {
				// 查询系统配置的noticeURL
				String noticeURL = h5HttpsURL + "/html5/app/notice/#/detail?noticeId=";
				for (NoticeMessageDTO messageDTO : noticeMessageDTOS) {
					NoticeMessageResponseVO.NoticeOutline message = new NoticeMessageResponseVO.NoticeOutline();
					message.setIsStick(messageDTO.getIsTop());
					message.setNoticeId(messageDTO.getId());
					message.setNoticeTime(simpleDateFormat.format(messageDTO.getTiming()));
					message.setNoticeTitle(messageDTO.getTitle());
					message.setNoticeURL(noticeURL + messageDTO.getId());

					responseVO.getMessageList().add(message);
				}
			}
		} catch (Exception e) {
			log.error("获取你我金融公告列表接口异常！{}", e.getMessage(), e);
		}
		return Result.with(responseVO);
	}

	@AuthIgnore
	@ApiOperation("查看公告详情（凡凯）")
	@PostMapping("/getNoticeDetail/{noticeId}")
	public Result<NiiwooNoticeMessageVO> getNoticeDetail(@PathVariable("noticeId") Long id) {
		NoticeMessageDTO noticeMessageDTO = homePageDubboService.getNoticeDetail(id);
		NiiwooNoticeMessageVO message = new NiiwooNoticeMessageVO();
		BeanUtils.copyProperties(noticeMessageDTO, message);
		return Result.with(message);
	}

	@AuthIgnore
	@ApiOperation("获取借款产品列表（凡凯）v5.1.5")
	@PostMapping("/getProductList")
	public Result<List<LoanBusinessVo>> getProductList() {
		List<LoanBusinessVo> productVoList = new ArrayList<>();

		List<LoanBusinessInfoDTO> productDTOList = loanBusinessDubboService.getProductList();
		for (LoanBusinessInfoDTO loanBusinessInfoDTO : productDTOList) {
			if (!Byte.valueOf("99").equals(loanBusinessInfoDTO.getProductType())) {
				LoanBusinessVo loanBusinessVo = new LoanBusinessVo();
				BeanUtils.copyProperties(loanBusinessInfoDTO, loanBusinessVo);
				productVoList.add(loanBusinessVo);
			}
		}

		return Result.with(productVoList);
	}

	@AuthIgnore
	@ApiOperation("获取借款产品列表")
	@PostMapping("/getProductList/v561")
	public Result<List<LoanBusinessVo>> getProductListV561() {
		List<LoanBusinessVo> productVoList = new ArrayList<>();

		List<LoanBusinessInfoDTO> productDTOList = loanBusinessDubboService.getProductList();
		for (LoanBusinessInfoDTO loanBusinessInfoDTO : productDTOList) {
			LoanBusinessVo loanBusinessVo = new LoanBusinessVo();
			BeanUtils.copyProperties(loanBusinessInfoDTO, loanBusinessVo);
			productVoList.add(loanBusinessVo);
		}

		return Result.with(productVoList);
	}

	@PostMapping("/appDownloadUrl")
	@AuthIgnore
	@ApiOperation("获取APP下载地址(刘春)")
	public Result<AppDownloadResponseVO> appDownloadUrl() {
		List<String> urls = projectCommonDubboService.getAppDownloadUrl();
		AppDownloadResponseVO appDownload = new AppDownloadResponseVO();
		appDownload.setAndroidUrl(urls.get(0));
		appDownload.setIosUrl(urls.get(1));
		return Result.with(appDownload);
	}

}
